package cn.com.chec.en.controller.front;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.com.chec.en.dao.ChannelInfoDao;
import cn.com.chec.en.dao.NewsInfoDao;
import cn.com.chec.en.dao.PageLinkDao;
import cn.com.chec.en.model.domain.ChannelInfo;
import cn.com.chec.en.model.domain.NewsInfo;
import cn.com.chec.en.model.dto.NewsDTO;

@Controller
public class JoinUsFrontController {
	protected static final Logger logger = Logger
			.getLogger(JoinUsFrontController.class);

	@Resource
	private PageLinkDao pageLinkDao;

	@Resource
	private ChannelInfoDao channelInfoDao;

	@Resource
	private NewsInfoDao newsInfoDao;

	@Resource
	private Map<String, Object> environment;

	@RequestMapping({ "/joinus" })
	public ModelAndView index(
			@RequestParam(value = "chId", required = false) String channelId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView("joinus");

		map.put("pageLinkMap", this.pageLinkDao.getAllAsMap());

		int defaultChannelId = 5;
		List<ChannelInfo> channelList = this.channelInfoDao.getSubListByParentIdLanguageId(
				1, defaultChannelId, 0, 2147483647);
		if ((channelList != null) && (channelList.size() > 0)) {
			defaultChannelId = ((ChannelInfo) channelList.get(0))
					.getChannelId();
		}
		map.put("channelList", channelList);

		int chId = (StringUtils.isNotBlank(channelId))
				&& (channelId.matches("\\d+")) ? Integer.valueOf(channelId)
				.intValue() : defaultChannelId;
		NewsDTO dto = this.newsInfoDao.getNewsDTOByChannelId(chId);
		ChannelInfo channelInfo = dto.getRel() != null ? dto.getRel()
				.getChannelnfo()
				: dto.getRel().getChannelnfo() == null ? new ChannelInfo()
						: new ChannelInfo();
		NewsInfo newsInfo = dto.getNewsInfo() != null ? dto.getNewsInfo()
				: new NewsInfo();
		map.put("channelInfo", channelInfo);
		map.put("newsInfo", newsInfo);

		map.putAll(this.environment);
		mav.addAllObjects(map);
		return mav;
	}
}